package com.wn.budget.service;

import com.wn.budget.model.*;
import com.wn.budget.repository.ProjectMaterialRepository;
import com.wn.budget.repository.ProjectSpaceRepository;
import com.wn.budget.repository.TemplateMaterialRepository;
import com.wn.budget.repository.TemplateSpaceRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author : linyuebin
 * @date : 2019/11/7
 */
@Service
public class TemplateService {
    @Autowired
    private TemplateSpaceRepository templateSpaceRepository;

    @Autowired
    private TemplateMaterialRepository templateMaterialRepository;

    @Autowired
    private ProjectSpaceRepository projectSpaceRepository;

    @Autowired
    private ProjectMaterialRepository projectMaterialRepository;

    /**
     * 新建工程，初始化模板
     *
     * @param templateId 模板id
     */
    public boolean initTemplate(String projectId, String templateId) {
        List<TemplateSpace> templateSpaces = templateSpaceRepository.findByTemplateId(templateId);

        List<ProjectSpace> projectSpaces = new ArrayList<>();
        int sort = 0;
        for (TemplateSpace templateSpace : templateSpaces) {
            ProjectSpace projectSpace = new ProjectSpace();

            projectSpace.setName(templateSpace.getSpaceName());
            projectSpace.setProjectId(projectId);
            projectSpace.setId(UUID.randomUUID().toString());
            projectSpace.setCreateDate(new Date());
            projectSpace.setSort(sort);

            projectSpaces.add(projectSpace);
            sort++;

            List<TemplateMaterial> templateMaterials = templateMaterialRepository.findByTemplateSpaceId(templateSpace.getId());

            List<ProjectMaterial> projectMaterials = new ArrayList<>();
            for (TemplateMaterial templateMaterial : templateMaterials) {
                ProjectMaterial projectMaterial = new ProjectMaterial();
                projectMaterial.setId(UUID.randomUUID().toString());
                projectMaterial.setCreateDate(new Date());
                projectMaterial.setMaterialId(templateMaterial.getMaterialId());
                projectMaterial.setQuantity(templateMaterial.getQuantity());
                projectMaterial.setProjectSpaceId(projectSpace.getId());
                projectMaterial.setProjectId(projectId);
                projectMaterials.add(projectMaterial);
            }
            projectMaterialRepository.saveAll(projectMaterials);
        }
        projectSpaceRepository.saveAll(projectSpaces);

        return true;
    }
}
